<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>收付款记录</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="receipt-payment">
      <search-btn-view btn-text="记录查询" :before-search="checkSearchValid" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button size="medium" type="primary" @click="addCostOrder">增加其他费用单</el-button>
          <el-button v-if="selectRecordList.length>0" size="medium" type="primary" @click="verificationRecords">批量核销</el-button>
          <el-button size="medium" type="primary" @click="exportExcel">导出excel</el-button>
        </template>
        <template slot="right">
          <table-col-show-select v-if="tableHideColumnKey!==null" :table-name="tableName" :current-column-name="currentColumnName"
            :hide-column.sync="tableHideColumnKey">
          </table-col-show-select>
        </template>
        <div slot="search-content">
          <search-form :search="search"></search-form>
        </div>
      </search-btn-view>
      <div v-if="statData!==null" class="receipt-payment-stat clearfix">
        <div>待审收款金额：{{statData.notAppReceiptSum}}</div>
        <div>待审收款折算金额：{{statData.notAppReceiptConversionSum}}</div>
        <div>待审付款金额：{{statData.notAppPaymentSum}}</div>
        <div>待审付款折算金额：{{statData.notAppPaymentConversionSum}}</div>
        <div>已审收款金额：{{statData.appReceiptSum}}</div>
        <div>已审收款折算金额：{{statData.appReceiptConversionSum}}</div>
        <div>已审付款金额：{{statData.appPaymentSum}}</div>
        <div>已审付款折算金额：{{statData.appPaymentConversionSum}}</div>
      </div>
      <div class="receipt-payment-table-div">
        <el-table fit stripe border ref="inoutPaymentRecord" :data="recordList" style="width: 100%" height="parent" @selection-change="toSelectData"
          :hide-column-keys="getTableHideColumns()" @row-click="lookDetail">
          <el-table-column :resizable="false" column-key="selection" key="selection" type="selection" width="40px" align="center"
            :selectable="checkSelectable"></el-table-column>
          <el-table-column :resizable="false" column-key="handle" key="handle" label="操作" fixed="left" header-align="center"
            :width="btnNum===0?60:btnNum*65">
            <template slot-scope="scope">
              <div class="table-btns clearfix">
                <template v-if="scope.row.hasApproval">
                  <el-button type="primary" size="mini" @click="approvalRecord(scope.row)">审核</el-button>
                  <el-button type="danger" size="mini" @click="retreatRecord(scope.row)">退回</el-button>
                </template>
                <template v-if="scope.row.hasInvoice">
                  <el-button type="primary" size="mini" @click="invoiceRecord(scope.row)">开票</el-button>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column sortable label="收付款单号" prop="receivePaymentId" key="receivePaymentId" min-width="130px" header-align="center">
          </el-table-column>
          <el-table-column sortable :resizable="false" label="类型" sort-by="type" column-key="type" key="type" min-width="65px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg(`receiptPayment.type.${scope.row.type}`)}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" label="来源" sort-by="source" column-key="source" key="source" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg(`receiptPayment.source.${scope.row.source}`)}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="金额" prop="sumMoney" key="sumMoney" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="折算金额" prop="conversionPrice" key="conversionPrice" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable label="收付方式" prop="receiptPaymentMode" key="receiptPaymentMode" min-width="100px" align="center">
          </el-table-column>
          <el-table-column sortable label="收付款方" prop="customerName" key="customerName" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable label="银行卡号" prop="relationBank" key="relationBank" min-width="180px" header-align="center"></el-table-column>
          <el-table-column sortable label="所属银行" prop="bank" key="bank" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable label="开票金额" prop="invoicePrice" key="invoicePrice" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" label="开票日期" prop="invoiceDate" key="invoiceDate" min-width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.invoiceDate!==''">{{moment(scope.row.invoiceDate).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable :resizable="false" label="收付款日期" prop="actualDay" key="actualDay" min-width="120px" align="center"></el-table-column>
          <el-table-column sortable :resizable="false" label="状态" sort-by="status" column-key="status" key="status" min-width="80px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg(`receiptPayment.status.${scope.row.status}`)}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="制单人" prop="createUserName" key="createUserName" min-width="100px" header-align="center">
          </el-table-column>
          <el-table-column sortable :resizable="false" label="制单时间" prop="createTime" key="createTime" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="审核人" prop="approvalUserName" key="approvalUserName" min-width="100px" header-align="center">
          </el-table-column>
          <el-table-column sortable :resizable="false" label="审核时间" prop="approvalTime" key="approvalTime" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.approvalTime!==''">{{moment(scope.row.approvalTime).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="是否核销" prop="isVerification" key="isVerification" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('warehouseBalance.detail.isVerification.'+scope.row.isVerification)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="核销人" prop="verificationUser" key="verificationUser" min-width="120px" header-align="center"></el-table-column>
          <el-table-column :resizable="false" label="核销时间" prop="verificationTime" key="verificationTime" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.verificationTime!==''">
                {{moment(scope.row.verificationTime).format('YYYY-MM-DD')}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="reason" key="reason" min-width="200px" header-align="center">
            <template slot-scope="scope">
              <span v-html="getTextHtml(scope.row.reason)"></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>

    <el-dialog fullscreen title="收付款明细" :visible.sync="openDetail" @closed="selectRecord=null">
      <div style="height:100%;overflow:auto">
        <detail-item v-if="openDetail" :record="selectRecord" @close="openDetail=false"></detail-item>
      </div>
    </el-dialog>

    <el-dialog title="增加其他费用单" :visible.sync="openCostOrder" top="10vh" width="60%">
      <div style="height:calc(80vh - 54px);overflow:auto">
        <cost-order :dropdown-option="dropdownOption" @cost-success="costSuccess"></cost-order>
      </div>
    </el-dialog>

    <el-dialog title="开票" :visible.sync="openInvoice" width="300px" top="calc(50vh - 110px)" @closed="selectRecord=null">
      <div style="height:160px;overflow:auto">
        <invoice-order v-if="openInvoice" :invoice="selectRecord" @invoice-success="invoiceSuccess"></invoice-order>
      </div>
    </el-dialog>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/searchBtnView.css",
    "./css/detailItem.css",
    "./css/costOrder.css",
    "./css/invoiceOrder.css"
  ], [
    "/vueSystem/i18n/index.js",
    "/vueSystem/js/permissionUtil.js",
    "/vueSystem/js/dropdownUtil.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/components/sysAutocomplete.js",
    "/vueSystem/components/filterSelect.js",
    "/remoteEquipment/board/components/boardSelect.js",
    "/vueSystem/mixins/tablePaginationMixin.js",
    "/vueSystem/mixins/linkageSelectMixin.js",
    "/vueSystem/models/baseModel.js"
  ]);
  importTableColShowConfigFiles();

</script>
<script src="./searchForm.js"></script>
<script src="./detailItem.js"></script>
<script src="./costOrder.js"></script>
<script src="./invoiceOrder.js"></script>

<script>
  var app = new Vue({
    el: '#app',
    mixins: [
      tablePaginationMixin(),
      tableColShowMixin('inoutPaymentRecord')
    ],

    data: function () {
      var search = {
        startTime: moment().startOf('month').valueOf(),
        endTime: moment().endOf('day').valueOf(),
        receiptPaymentMode: '',
        createUser: '',
        customerName: '',
        relationBank: '',
        bank: '',
        type: '',
        status: '',
        isVerification: '',
        startMoney: undefined,
        endMoney: undefined
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        recordList: [],
        selectRecordList: [],
        statData: null,
        user: null,
        openDetail: false,
        openCostOrder: false,
        openInvoice: false,
        selectRecord: null,
        dropdownOption: {},
        i18n: i18n,
        moment: moment,
        btnNum: 0
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setUser().then(function () {
        self.loading = false;
        self.setRecordList(true, true);
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      checkSearchValid: function () {
        var search = this.search;
        var startTime = search.startTime;
        var endTime = search.endTime;
        if (startTime !== null && endTime !== null) {
          if (moment(startTime).isAfter(moment(endTime), 'second')) {
            this.$alert('收付款的开始时间不能大于结束时间', '信息');
            return false;
          }
        }
        return true;
      },

      setRecordList: function (isSearch, hasSum) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        };

        this.setPostData(postData, this.search);

        if (hasSum) {
          postData.isSum = true;
        }

        this.loading = true;
        var self = this;
        var user = this.user;
        ajaxRequest('finance/getReceivePaymentRecord', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var pageData = res.pageData;
          if (hasSum) {
            self.statData = res.sumData
          }

          var recordList = pageData.returnData;
          if (currentPage !== 1 && recordList.length === 0) {
            self.pagination.totalCount = pageData.iTotalRecords;
            self.$nextTick(function () {
              self.setRecordList(isSearch, hasSum);
            });
            return;
          }
          for (var i = 0; i < recordList.length; i++) {
            var record = recordList[i];
            record.createTime = SysUtil.formatString2Date(record.createTime);
            record.approvalTime = SysUtil.formatString2Date(record.approvalTime);
            var status = record.status;
            if (status !== 1) {
              record.approvalUserName = '';
            }
            var verificationTime = record.verificationTime;
            if (SysUtil.isEmpty(verificationTime)) {
              record.verificationTime = '';
            }
            var invoiceDate = record.invoiceDate;
            var hasInvoice;
            if (invoiceDate === null) {
              record.invoiceDate = '';
              record.invoicePrice = '';
              hasInvoice = true;
            } else {
              record.invoiceDate = moment(invoiceDate).valueOf();
              hasInvoice = false;
            }

            var btnNum = 0;
            if (status === 0 && record.isCanApproval === 1) {
              record.hasApproval = true;
              btnNum += 2;
            } else {
              record.hasApproval = false;
            }
            if (hasInvoice) {
              if ([0, 1].indexOf(status) !== -1) {
                btnNum += 1;
              } else {
                hasInvoice = false;
              }
            }
            record.hasInvoice = hasInvoice;
            record.btnNum = btnNum;
          }

          self.btnNum = self.getBtnNum(recordList);

          self.recordList = recordList;
          self.pagination.totalCount = pageData.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setPostData: function (postData, search) {
        var startTime = search.startTime;
        if (startTime !== null) {
          postData.startTime = moment(startTime).format('YYYY-MM-DD HH:mm:ss');
        }
        var endTime = search.endTime;
        if (endTime !== null) {
          postData.endTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss');
        }

        var createUser = search.createUser;
        if (createUser !== '') {
          postData.createUser = createUser.createUser;
        }

        var customerName = search.customerName;
        if (customerName !== '') {
          postData.receviePaymentUserName = customerName;
        }

        var fields = ['receiptPaymentMode', 'relationBank', 'bank', 'type', 'status', 'isVerification', 'startMoney',
          'endMoney'
        ];
        SysUtil.setPostData(postData, search, fields);
      },

      getBtnNum: function (recordList) {
        var record = _.maxBy(recordList, 'btnNum');
        if (record === undefined) {
          return 0;
        }
        return record.btnNum;
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setRecordList(true, true);
      },

      pageChange: function () {
        this.setRecordList();
      },

      approvalRecord: function (record) {
        this.toUpdateRecordStatus(record, 1);
      },

      retreatRecord: function (record) {
        var self = this;
        this.$confirm('是否退回该条收付款记录?', '退回确认').then(function () {
          self.toUpdateRecordStatus(record, 2);
        }).catch(function () {});
      },

      toUpdateRecordStatus: function (record, status) {
        this.loading = true;
        var self = this;
        ajaxRequest('finance/approvalReceiptPaymentRecord', {
          receivePaymentId: record.receivePaymentId,
          status: status
        }).then(function () {
          var msg = status === 1 ? '审核通过' : '成功退回';
          msg = '该收付款记录' + msg;
          self.$alert(msg, '信息', {
            callback: function () {
              self.setRecordList(false, true);
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      lookDetail: function (row, column) {
        var columnKey = column.columnKey;
        if (columnKey === 'handle') {
          return;
        }

        this.selectRecord = row;
        this.openDetail = true;
      },

      toSelectData: function (recordList) {
        this.selectRecordList = recordList;
      },

      checkSelectable: function (record) {
        if (record.status !== 1) {
          return false;
        }
        var relationBank = record.relationBank;
        return record.isVerification === 0 && !SysUtil.isEmpty(relationBank);
      },

      verificationRecords: function () {
        var recordList = this.selectRecordList;
        if (recordList.length === 0) {
          this.$alert('请选择需要核销的记录', '信息');
          return;
        }

        var ids = _.map(recordList, 'receivePaymentId');
        this.loading = true;
        var self = this;
        ajaxRequest('finance/verificationReceiptPaymentRecord', {
          idArray: JSON.stringify(ids)
        }).then(function () {
          self.loading = false;
          self.$alert('收付款记录成功核销', '信息', {
            callback: function () {
              self.setRecordList(false, true);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      addCostOrder: function () {
        this.openCostOrder = true;
      },

      costSuccess: function () {
        this.openCostOrder = false;
        this.setRecordList(false, true);
      },

      invoiceRecord: function (record) {
        this.selectRecord = record;
        this.openInvoice = true;
      },

      invoiceSuccess: function () {
        this.openInvoice = false;
        this.setRecordList();
      },

      getTextHtml: function (text) {
        if (SysUtil.isEmpty(text)) {
          return '';
        }
        var htmlText = _.escape(text);
        htmlText = htmlText.replace(/ /g, '&nbsp;').replace(/\n/g, '<br>');
        return htmlText;
      },

      exportExcel: function () {
        var postData = {};
        this.setPostData(postData, this.oldSearch);
        var formParam = SysUtil.formatFormParam(postData);
        var basePath = SysUtil.getBasePath();
        var path = `${basePath}/finance/exportReceivePaymentRecord?${formParam}`;
        window.open(path);
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SearchForm: SearchForm,
      DetailItem: DetailItem,
      CostOrder: CostOrder,
      InvoiceOrder: InvoiceOrder
    }
  });

</script>
<style>
  .receipt-payment {
    padding: 10px 20px 5px;
    height: calc(100% - 15px);
    position: relative;
    display: flex;
    flex-direction: column;
  }

  .receipt-payment .receipt-payment-stat {
    margin-bottom: 5px;
  }

  .receipt-payment .receipt-payment-stat>div {
    float: left;
    margin-right: 10px;
  }

  .receipt-payment .receipt-payment-stat>div:last-child {
    margin-right: 0;
  }

  .receipt-payment .receipt-payment-table-div {
    flex: 1;
    overflow: auto;
  }

  .receipt-payment .receipt-payment-table-div .table-btns>.el-button {
    float: left;
  }

  .receipt-payment .receipt-payment-table-div .el-button+.el-button {
    margin-left: 8px;
  }

  .search-form .el-form-item {
    margin-bottom: 10px;
  }

  .search-form .search-input {
    width: 200px;
  }

</style>

</html>
